'use client'

import React, { createContext, useContext, useState, useEffect } from 'react'

const AuthContext = createContext({})

export function AuthProvider({ children }) {
    const [user, setUser] = useState(null)
    const [loading, setLoading] = useState(true)

    // 从localStorage恢复用户状态
    useEffect(() => {
        try {
            const savedUser = localStorage.getItem('user')
            if (savedUser) {
                setUser(JSON.parse(savedUser))
            }
        } catch (error) {
            console.error('Failed to restore user from localStorage:', error)
        } finally {
            setLoading(false)
        }
    }, [])

    // 登录函数
    const login = (userData) => {
        setUser(userData)
        localStorage.setItem('user', JSON.stringify(userData))
    }

    // 登出函数
    const logout = () => {
        setUser(null)
        localStorage.removeItem('user')
    }

    // 更新用户信息
    const updateUser = (userData) => {
        const updatedUser = { ...user, ...userData }
        setUser(updatedUser)
        localStorage.setItem('user', JSON.stringify(updatedUser))
    }

    // 检查是否已登录
    const isAuthenticated = !!user

    const value = {
        user,
        login,
        logout,
        updateUser,
        isAuthenticated,
        loading
    }

    return (
        <AuthContext.Provider value={value}>
            {children}
        </AuthContext.Provider>
    )
}

export function useAuth() {
    const context = useContext(AuthContext)
    if (!context) {
        throw new Error('useAuth must be used within an AuthProvider')
    }
    return context
}